package com.example.download.utils
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.*
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.concurrent.TimeUnit


/**
 * Created by  you
 * Date: 2022/3/24
 * Time: 14:27
 * mp4 下载
 */
class DowLoadUtils(
    private val fileUrl: String,
    private val filePath: String,
    val onSuccessListener: (file:File,Int, String) -> Unit,
    val onFailureListener: () -> Unit
) {
    private var call: Call? = null
    companion object {
        //判断当前下载任务是否结束
        var isDownLoading = false
    }

    fun loadFile() {
        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .build()
        val request = Request.Builder()
            .url(fileUrl)
            .build()
        call = okHttpClient.newCall(request)
        call?.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                GlobalScope.launch(Dispatchers.Main) {
                    onFailureListener.invoke()
                    isDownLoading = false
                }

            }

            override fun onResponse(call: Call, response: Response) {
                var responseBody: ResponseBody? = null
                var bis: BufferedInputStream? = null
                var fos: FileOutputStream? = null
                try {
                    if (response.isSuccessful) {
                        if (call.isCanceled()) return
                        isDownLoading = true
                        responseBody = response.body
                        val total = responseBody!!.contentLength()
                        bis = BufferedInputStream(responseBody.byteStream())
                        val file = File(filePath, FileSavaUtils.getFileNameByUrl(fileUrl))
                        fos = FileOutputStream(file)
                        val bytes = ByteArray(1024 * 8)
                        var len: Int
                        var current: Long = 0
                        while (bis.read(bytes).also { len = it } != -1) {
                            fos.write(bytes, 0, len)
                            fos.flush()
                            current += len.toLong()
                            //计算进度
                            val progress = (100 * current / total).toInt()
                            Log.i("TAGss", "onResponse: ${numFormat(current / 1024f / 1024f)}MB")
                            GlobalScope.launch(Dispatchers.Main) {
                                onSuccessListener.invoke(
                                    file,
                                    progress,
                                    numFormat(current / 1024f / 1024f)
                                )
                            }
                        }
                    }
                } catch (e: Exception) {
                    GlobalScope.launch(Dispatchers.Main) {
                        isDownLoading = false
                        onFailureListener.invoke()
                    }
                } finally {
                    isDownLoading = false
                    responseBody?.close()
                    bis?.close()
                    fos?.close()
                }
            }

        })
    }
    fun cancelDownLoad() {
        isDownLoading = false
        call?.cancel()
    }


}